<template>
  <div class='search'>
    <div class="flex">
      <div class='back'>
        <router-link to="/main/index"><i class="fa fa-chevron-left icon"></i></router-link>
      </div>
      <div class='flex-item'>
        <mu-auto-complete @focus='onFocus' underline-color="#ff4081" :data="searchRes" :filter="filter" full-width='true'
          v-model="searchKey" placeholder="搜索漫画" avatar>
          <template slot-scope="scope">
            <mu-list-item :to="{path:'/main/comicInfo',query:{comicId:scope.item.comic_id}}">
              <mu-list-item-action>
                <mu-avatar>
                  <img v-lazy="'http://image.mhxk.com/mh/'+scope.item.comic_id+'.jpg-noresize.webp'">
                </mu-avatar>
              </mu-list-item-action>
              <mu-list-item-content v-value="scope.item.comic_id">
                <mu-list-item-title v-html='scope.highlight'></mu-list-item-title>
                <mu-list-item-sub-title>{{scope.item.cartoon_author_list_name}}</mu-list-item-sub-title>
              </mu-list-item-content>
              <mu-list-item-action>
                <b style='font-size:12px;color:#56b6e7;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;'>{{scope.item.last_chapter_name}}</b>
              </mu-list-item-action>
            </mu-list-item>
          </template>
        </mu-auto-complete>
      </div>
    </div>
    <div class="hotKey">
      <router-link :to="{path:'/main/comicInfo',query:{comicId:key.comic_id}}" v-for="key, index in hotKey" :key="key">
        <mu-chip :color="key.color" :text-color='white'>
          <mu-avatar :size="28">
            <img v-lazy="'http://image.mhxk.com/mh/'+key.comic_id+'.jpg-noresize.webp'">
          </mu-avatar>
          {{key.comic_name}}
        </mu-chip>
      </router-link>
    </div>
    <mu-divider></mu-divider>
    <mu-list v-if="hisList.length>0">
      <mu-sub-header>
        <div class="flex">
          <span>搜索历史</span><span @click='onClear' class='clear'>清空</span>
        </div>
      </mu-sub-header>
      <mu-list-item @click='clickHis(his)' avatar button v-for="his,index in hisList" :key="his.id" :ripple="false">
        <mu-list-item-action>
          <mu-avatar :size="22">
            {{his.substring(0, 1)}}
          </mu-avatar>
        </mu-list-item-action>
        <mu-list-item-title> {{his}} </mu-list-item-title>
        <mu-list-item-action>
          <i @click='removeHis(index)' class="fa fa-remove" aria-hidden="true"></i>
        </mu-list-item-action>
      </mu-list-item>
    </mu-list>
    <mu-divider></mu-divider>
    <mh_recomend :data='recommend'></mh_recomend>
    <!-- <mu-grid-list class="gridlist-inline" :cols="3">
      <mu-grid-tile v-for="item, index in recommend" :key="index">
        <img v-lazy="item.pic">
        <span slot="title">{{item.title}}</span>
        <!-- <span slot="subTitle">by <b>{{item.author}}</b></span> 
    <div class='score' slot="action">
      <b>{{item.score}}</b>
    </div>
    </mu-grid-tile>
    </mu-grid-list> -->
  </div>
</template>
<style>
  @import 'search';

</style>
<script>
  import mh_recomend from './components/recommend/index';
  import T from './../util/tool.js'
  export default {
    components: {
      mh_recomend
    },
    data() {
      return {
        hotKey: [],
        searchRes: [],
        searchKey: '',
        recommend: [],
        tcolor: '',
        history: null,
        hisList: []
      };
    },
    methods: {
      toInfo(id) {
        console.log(id);

      },
      clickHis(his) {
        console.log(this.searchKey);

        his = his == null ? his = this.searchKey : his = his;
        debugger;
        return false;
        // if (typeof his == 'string')
        this.$router.push('/main/sort?key=' + his);
      },
      // 移除搜索历史
      removeHis(index) {
        this.hisList.splice(index, 1);
        this.history.setItem('his', this.hisList.toString());
      },
      onClear() {
        this.history.removeItem('his').then(() => {
          // 当值被移除后，此处代码运行
          this.hisList = [];
        });
      },
      // 获取焦点时显示搜索历史记录
      onFocus() {
        this.history.getItem('his').then(val => {
          if (val) {
            val = decodeURI(val);
            let tempArr = Array.from(new Set(val.split(',')));
            this.hisList = tempArr.reverse();
          }
        })
      },
      randColor() {
        let color =
          "#" +
          ("00000" + ((Math.random() * 0x1000000) << 0).toString(16)).substr(-6);
        return color;

      },
      ColorReverse(OldColorValue) {
        var OldColorValue = "0x" + OldColorValue.replace(/#/g, "");
        var str = "000000" + (0xFFFFFF - OldColorValue).toString(16);
        // return str.substring(str.length-6,str.length);
        return "#" + str.substring(str.length - 6, str.length);
      },
      getValueByItem(item) {
        if (!item) return '';
        return typeof item === 'string' ? item : item.comic_name;
      },
      filter(value, item, highlight) {
        return this.getSearchData()
      },
      getSearchData() {
        if (!this.searchKey) return false;
        let key = encodeURI(this.searchKey);
        // 获取历史搜索
        this.history.getItem('his').then(val => {
          if (val) {
            let tempArr = val.split(',');
            let index = tempArr.indexOf(key);
            if (index != -1) {
              tempArr.splice(index, 1);
            }
            // tempArr.push(key);
            val = tempArr.toString();
          }
          this.history.setItem('his', val ? (val + ',' + key) : key);
        })
        let results = [];
        this.$http.get(`http://y.yuduo.top/index/manhua/search/?key=${key}`).then(res => {
          let result = res.status == 200 && res.data ? JSON.parse(res.data) : '';
          this.searchRes = result.data.slice(0, 15);
          this.searchRes.map(item => {
            const value = this.getValueByItem(item);
            const index = value.toLowerCase().indexOf(this.searchKey.toLowerCase());
            // if (index === -1) continue;
            const before = value.substring(0, index);
            const highlight = value.substring(index, index + this.searchKey.length);
            const after = value.substring(index + this.searchKey.length);
            results.push({
              item: item,
              highlight: [
                before,
                `<span class="mu-secondary-text-color">${highlight}</span>`,
                after,
                `<`
              ].join('')
            });
          });
        })
        return results;
      },
    },
    mounted() {
      // lghistory.setItem('name', '张三')
      // this.$vlf.config({
      //   'name': 'mh',
      //   'storeName': 'history',
      //   version: '0.0.1'
      // });
      // console.log(this.$vlf);

      // 获取热门搜索词
      this.$http.get('http://y.yuduo.top/index/manhua/getHotSearch').then(res => {
        let result = res.status == 200 && res.data ? JSON.parse(res.data) : '';
        this.hotKey = T.formatKey(T.shuffle(result.data));
        this.hotKey.map(item => {
          item.color = this.randColor();
        })
      })
      this.$http.get('http://y.yuduo.top/index/Manhua/recommend').then(res => {
        let result = res.status == 200 && res.data ? res.data : '';
        this.recommend = T.shuffle(result).splice(0, 3);
      })
    },
    created() {
      this.$vlf.createInstance({
        name: 'mh',
        storeName: 'history',
        verison: '0.0.1',
        size: 4399
      }).then(his => {
        this.history = his;
      });
    }
  };

</script>
